<script setup lang="ts">
import { ref,onMounted,toRaw,h } from "vue";
import {deviceDetection, getKeyList} from "@pureadmin/utils";
import {addDialog,closeDialog} from "@/components/ReDialog/index";
import addVisitForm from "./addVisitForm.vue";
import {customerIndex, customerLogs, getCustomerDetail} from "@/api/crm";
import {customerTaskApi} from "@/api/task";
import {message} from "@/utils/message";
import TaskDetailView from "@/views/task/list/detail.vue";


// 声明 props 类型
export interface FormProps {
  formInline: {

  };
}
const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({  })
});


onMounted(() => {
  getCustomerInfo()
});

// 查看任务详情
const viewTaskDetail = (taskData: any) => {
  addDialog({
    title: "任务详情",
    props: {
      taskData: taskData
    },
    width: "600px",
    draggable: true,
    fullscreenIcon: true,
    hideFooter: true,
    contentRenderer: () => h(TaskDetailView, {
      taskData: taskData
    })
  });
};

const newFormInline = ref(props.formInline);
const log_column = [
  {label: "操作类型", prop: "log_type",width:120,},
  {label: "操作人员",width:120,prop: "creator"},
  {label: "操作时间", width: 140, prop: "created_at"},
  {label: "备注",width: 220, showOverflowTooltip:true, prop: "remark"},
  {label: "描述",showOverflowTooltip:true,minWidth: 200,prop: "content"},
];

const customerInfo = ref(props.formInline);
const customerTasks = ref([]);

const getCustomerInfo = async function () {
  const {data} = await getCustomerDetail({id:newFormInline.value});
  customerInfo.value = data;
  // 同时获取客户的跟进任务
  await getCustomerTasks();
}

// 获取客户的跟进任务
const getCustomerTasks = async function () {
  try {
    const {data} = await customerTaskApi.getCustomerTasks(newFormInline.value);
    customerTasks.value = data || [];
  } catch (error) {
    console.error("获取客户任务失败:", error);
    customerTasks.value = [];
  }
}

const formRef = ref();
function addVisitLog(id){
  function saveVisitLog(options,index){
    const FormRef = formRef.value.getRef();
    const curData = options.props.formInline;
    curData.customer_id = id;
    FormRef.validate(valid => {
      if (valid) {
        customerLogs(curData, "post").then(res => {
          if (res.code === 0) {
            message(`您已成功提交的这条回访数据`, { type: "success" });
            closeDialog(options, index);
            customerInfo.value.visit_logs = res.data;
          } else {
            message(`回访失败，原因：${res.message}`, {type: "error"});
          }
        })
      }
    });
  }
  addDialog({
    title: `新增回访记录`,
    props: {
      formInline: JSON.parse(JSON.stringify( {})),//type1编辑，2浏览
    },
    width: "40%",
    draggable: true,
    hideFooter:false,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(addVisitForm, {ref: formRef, formInline: null}),
    footerButtons: [
      { label: "取消",size: "small",type: "info", btnClick: ({ dialog: { options, index }, button }) => {closeDialog(options, index);}},

      {label: "提交",size: "small",type: "success",
        btnClick: ({ dialog: { options, index }, button }) => {
          saveVisitLog(options,index)
        }
      }
    ],
  });
}

</script>

<template>
  <re-col>
    <el-card class="custom-card" shadow="never">
      <h5>客户信息</h5>
      <el-descriptions :column="4" border size="small">
        <el-descriptions-item label="客户Id" label-width="120px">{{customerInfo.id||'-'}}</el-descriptions-item>
        <el-descriptions-item label="客户姓名" label-width="120px">{{customerInfo.fullname||'-'}}</el-descriptions-item>
        <el-descriptions-item label="邮箱" label-width="120px">{{customerInfo.email||'-'}}</el-descriptions-item>
        <el-descriptions-item label="电话号码" label-width="120px">{{customerInfo.contact||'-'}}</el-descriptions-item>
        <el-descriptions-item label="Ip" label-width="120px">{{customerInfo.ip||'-'}}</el-descriptions-item>
        <el-descriptions-item label="系统" label-width="120px">{{customerInfo.sysinfo?.os||'-'}}</el-descriptions-item>
        <el-descriptions-item label="浏览器">{{customerInfo.sysinfo?.browser||'-'}}</el-descriptions-item>
        <el-descriptions-item label="语言">{{customerInfo.sysinfo?.language||'-'}}</el-descriptions-item>
        <el-descriptions-item label="时区">{{customerInfo.sysinfo?.timezone||'-'}}</el-descriptions-item>
        <el-descriptions-item label="分辨率">{{customerInfo.sysinfo?.screen_size||'-'}}</el-descriptions-item>
        <el-descriptions-item label="初始金额">{{customerInfo.init_spent||'-'}}USD</el-descriptions-item>
        <el-descriptions-item label="当日金额">{{customerInfo.today_spent||'-'}}USD</el-descriptions-item>
        <el-descriptions-item label="累计金额">{{customerInfo.total_spent||'-'}}USD</el-descriptions-item>
        <el-descriptions-item label="订单笔数">{{customerInfo.orders_count||'0'}}笔</el-descriptions-item>
        <el-descriptions-item label="首次付款时间">{{customerInfo.frist_pay_at||'-'}}</el-descriptions-item>
        <el-descriptions-item label="最后付款时间">{{customerInfo.last_pay_at||'-'}}</el-descriptions-item>
        <el-descriptions-item label="viewport_size">{{customerInfo.sysinfo?.viewport_size||'-'}}</el-descriptions-item>
        <el-descriptions-item label="邮箱" show-overflow-tooltip>{{customerInfo.email||'-'}}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions  border size="small">

        <el-descriptions-item label="浏览器代理信息" label-width="120px" >{{customerInfo.sysinfo?.user_agent||'-'}}</el-descriptions-item>
      </el-descriptions>

    </el-card>
    <el-card class="custom-card" shadow="never" size="small">
      <el-tabs class="bg-bg_color  w-[99/100]  pt-[1px] overflow-auto" style="margin-top:-8px;" >
        <el-tab-pane label="独立站订单" name="0">
          <el-table :data="customerInfo.orders" style="width: 100%" size="small">
            <el-table-column prop="id" label="订单号" width="80" />
            <el-table-column prop="order_number" label="订单编号" width="125" />
            <el-table-column prop="total_price" label="订单金额" width="90" >
              <template #default="scope">
                {{scope.row.currency_code!='USD'?((scope.row.total_price/scope.row.currency_rate).toFixed(2)):scope.row.total_price}}
              </template>
            </el-table-column>
            <el-table-column prop="diy_status_text" label="跟进状态" width="90" ></el-table-column>
            <el-table-column prop="diy_remark" label="跟进记录" width="90" show-overflow-tooltip></el-table-column>
            <el-table-column prop="diy_sales_name" label="跟进人" width="90" ></el-table-column>
            <el-table-column prop="diy_allo_at" label="分配时间" width="130" ></el-table-column>
            <el-table-column prop="store_url" show-overflow-tooltip label="店铺地址"  />
            <el-table-column prop="pay_at" label="付款时间" width="150" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="马帮订单" name="">
          <el-table :data="customerInfo.mb_orders" style="width: 100%" size="small">
            <el-table-column prop="id" label="订单号" width="80" />
            <el-table-column prop="platform_order_id" label="订单编号" width="130" show-overflow-tooltip />
            <el-table-column prop="order_fee_usd" label="订单金额" width="100" >
              <template #default="scope">
                {{(+scope.row.order_fee_usd).toFixed(2)}}
              </template>
            </el-table-column>

            <el-table-column prop="shop_id_text" label="店铺" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="track_number" label="追踪单号" width="100" show-overflow-tooltip ></el-table-column>
            <el-table-column prop="order_ellipsis_other_title" show-overflow-tooltip label="品类"  />
            <el-table-column prop="paid_time_text" label="付款时间" width="130" />
            <el-table-column prop="order_status_text" label="状态" width="70" />
<!--            <el-table-column prop="sales_record_number" label="sales_record_number" width="100" />-->
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-card class="custom-card" shadow="never" size="small">
      <h5>收件地址列表</h5>
      <el-table :data="customerInfo.addresses" style="width: 100%" size="small">
        <el-table-column prop="id" label="Id" width="80" />
        <el-table-column prop="name" label="姓名" width="80" />
        <el-table-column prop="phone" label="手机号" width="80" />
        <el-table-column prop="default" label="是否默认"  >
          <template #default="scope">
            {{scope.row.default?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column prop="country_name" label="国家" width="80" />
        <el-table-column prop="province" label="省份" width="90" ></el-table-column>
        <el-table-column prop="city" label="城市" width="90" ></el-table-column>
        <el-table-column prop="area" label="地区" width="90" ></el-table-column>
        <el-table-column prop="zip" label="邮编" width="90" ></el-table-column>
        <el-table-column prop="company" label="公司名" width="90" ></el-table-column>
        <el-table-column prop="address1" show-overflow-tooltip label="地址1" width="120" />
        <el-table-column prop="address2" show-overflow-tooltip label="地址1" width="120" />
      </el-table>
    </el-card>

    <el-card class="custom-card" shadow="never">
      <h5>跟进任务</h5>
      <el-table :data="customerTasks" style="width: 100%" size="small">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="任务类型" width="120">
          <template #default="scope">
            {{scope.row.task_type?.name || '-'}}
          </template>
        </el-table-column>
        <el-table-column label="优先级" width="80" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.priority === 4 ? 'danger' : scope.row.priority === 3 ? 'warning' : scope.row.priority === 2 ? 'info' : 'success'"
              size="small"
            >
              {{scope.row.priority === 4 ? '紧急' : scope.row.priority === 3 ? '高' : scope.row.priority === 2 ? '中' : '低'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="跟进人" width="100">
          <template #default="scope">
            {{scope.row.follower?.username || '-'}}
          </template>
        </el-table-column>
        <el-table-column label="任务状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 0 ? 'info' : scope.row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{scope.row.status === 0 ? '待处理' : scope.row.status === 1 ? '已完成' : '超时完成'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="跟进反馈" width="100" show-overflow-tooltip>
          <template #default="scope">
            {{scope.row.feedback_text || '-'}}
          </template>
        </el-table-column>


        <el-table-column label="" width="60" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1 || scope.row.status === 2"
              type="primary"
              link
              size="small"
              @click="viewTaskDetail(scope.row)"
            >
              详情
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="截止时间" width="150">
          <template #default="scope">
            {{scope.row.deadline_at ? new Date(scope.row.deadline_at * 1000).toLocaleString() : '-'}}
          </template>
        </el-table-column>
        <el-table-column label="指派时间" width="150">
          <template #default="scope">
            {{scope.row.created_at || '-'}}
          </template>
        </el-table-column> -->
        <el-table-column label="完成时间" width="150">
          <template #default="scope">
            {{scope.row.completed_at ? new Date(scope.row.completed_at * 1000).toLocaleString() : '-'}}
          </template>
        </el-table-column>
        <el-table-column label="备注" show-overflow-tooltip>
          <template #default="scope">
            {{scope.row.remark || '-'}}
          </template>
        </el-table-column>

      </el-table>
    </el-card>


    <el-card class="custom-card" shadow="never">
      <h5>回访<el-button link type="primary" @click="addVisitLog(customerInfo.id)">增加回访记录</el-button></h5>
      <el-table :data="customerInfo.visit_logs" style="width: 100%" size="small">
        <el-table-column prop="id" label="Id" width="80" />
        <el-table-column prop="visit_time" label="回访日期" width="120" />
        <el-table-column prop="saleman_id" label="回访人员" width="80" />
        <el-table-column prop="default" label="截图证明"  >
          <template #default="scope">
            <el-image style="width: 40px; height: 40px" :src="scope.row.picture[0]" :preview-src-list="scope.row.picture" :preview-teleported="true" />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="130" />
        <el-table-column prop="audit_at" label="审核时间" width="130" ></el-table-column>
        <el-table-column prop="audit_id" label="审核人员" width="90" ></el-table-column>
        <el-table-column prop="audit_status" label="审核状态" width="90" ></el-table-column>
        <el-table-column prop="remark" show-overflow-tooltip label="备注" width="120" />
      </el-table>
    </el-card>
    <el-card class="custom-card" shadow="never">
      <h5>操作记录</h5>
      <pure-table  size="small" :data="customerInfo.logs" :columns="log_column"/>
    </el-card>
  </re-col>

</template>
<style scoped>
:deep(.el-card) {
  border: none;
}
:deep(.el-card h5) {
  margin-bottom: 10px;
}
</style>
